package cn.endeavour.order.service.impl;


import cn.endeavour.basic.service.impl.BaseServiceImpl;
import cn.endeavour.basic.util.CodeGenerateUtils;
import cn.endeavour.basic.util.LoginContextUtil;
import cn.endeavour.basic.util.PageList;
import cn.endeavour.order.domain.AdoptOrder;
import cn.endeavour.order.domain.OrderAddress;
import cn.endeavour.order.mapper.AdoptOrderMapper;
import cn.endeavour.order.mapper.OrderAddressMapper;
import cn.endeavour.order.mapper.ProductOrderDetailMapper;
import cn.endeavour.order.mapper.ProductOrderMapper;
import cn.endeavour.order.query.AdoptOrderQuery;
import cn.endeavour.order.service.IAdoptOrderService;
import cn.endeavour.org.domain.Employee;
import cn.endeavour.org.mapper.EmployeeMapper;
import cn.endeavour.pay.constants.PayConstants;
import cn.endeavour.pay.domain.PayBill;
import cn.endeavour.pay.mapper.PayBillMapper;
import cn.endeavour.pay.service.IPayBillService;
import cn.endeavour.pet.domain.Pet;
import cn.endeavour.pet.mapper.PetMapper;
import cn.endeavour.quartz.constants.JobConstants;
import cn.endeavour.quartz.domain.QuartzJobInfo;
import cn.endeavour.quartz.service.IQuartzService;
import cn.endeavour.user.domain.LoginInfo;
import cn.endeavour.user.domain.User;
import cn.endeavour.user.domain.UserAddress;
import cn.endeavour.user.mapper.UserAddressMapper;
import cn.endeavour.user.mapper.UserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class AdoptOrderServiceImpl extends BaseServiceImpl<AdoptOrder> implements IAdoptOrderService {

    @Autowired
    private UserAddressMapper userAddressMapper;

    @Autowired
    private OrderAddressMapper orderAddressMapper;

    @Autowired
    private PetMapper petMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private AdoptOrderMapper adoptOrderMapper;

    @Autowired
    private IPayBillService payBillService;

    @Autowired
    private PayBillMapper payBillMapper;

    @Autowired
    private IQuartzService quartzService;

    @Override
    @Transactional
    public String adoptOrderSubmit(Map<String, Object> params, HttpServletRequest request) {
        // 获取地址id
        Long addressId = Long.parseLong(params.get("address_id").toString());
        // 送货方式 - 默认送宠上门
        Integer service_method = Integer.parseInt(params.get("service_method").toString());
        // 支付方式
        Long payType = Long.parseLong(params.get("pay_method").toString());
        // 宠物id
        Long petId = Long.parseLong(params.get("pet_id").toString());
        // 通过id查询
        Pet pet = petMapper.loadById(petId);
        // 获取登录人信息
        LoginInfo loginInfo = LoginContextUtil.getLoginInfo(request);
        // 通过loginInfo来查询用户信息
        User user = userMapper.loadByLoginInfoId(loginInfo.getId());
        // 给pet的领养人设置id
        pet.setUser_id(user.getId());
        // 设置下架
        pet.setState(0);
        // 设置领养时间
        pet.setOffSaleTime(new Date());
        // 进行保存
        petMapper.updateAdopt(pet);
        // 创建订单
        // 将宠物信息和用户信息转换为领养订单
        AdoptOrder adoptOrder = petUser2AdoptOrder(pet, user);
        // 进行保存 返回自增主键
        adoptOrderMapper.save(adoptOrder);
        // 获取到用户地址
        UserAddress userAddress = userAddressMapper.loadById(addressId);
        // 将用户地址转换为订单地址
        OrderAddress orderAddress = userAddress2OrderAddress(userAddress, adoptOrder);
        // 保存
        orderAddressMapper.save(orderAddress);
        // 支付
        PayBill payBill = initPayBill(user, adoptOrder, payType);
        payBillMapper.save(payBill);
        String payRequest = payBillService.payRequest(payBill);
        // 生成定时器
        QuartzJobInfo info = new QuartzJobInfo();
        info.setTime(payBill.getLastPayTime());
        info.setType(JobConstants.OVER_TIME_NO_PAY_ADOPT);
        info.setJobName(JobConstants.OVER_TIME_NO_PAY_ADOPT + payBill.getUnionPaySn());
        HashMap<String, Long> map = new HashMap<>();
        map.put("orderId", adoptOrder.getId());
        quartzService.addJob(info);
        return payRequest;
    }

    private PayBill initPayBill(User user, AdoptOrder adoptOrder, Long payType) {
        PayBill payBill = new PayBill();
        payBill.setDigest(adoptOrder.getDigest());
        payBill.setMoney(adoptOrder.getPrice());
        payBill.setLastPayTime(new Date(System.currentTimeMillis() + PayConstants.ORDER_TIMEOUT));
        payBill.setPayChannel(payType);
        payBill.setUnionPaySn(adoptOrder.getPaySn());
        payBill.setBusinessType(PayConstants.BUSINESS_TYPE_ADOPT);
        payBill.setBusinessKey(adoptOrder.getId());
        payBill.setUser_id(adoptOrder.getUser_id());
        payBill.setNickName(user.getUsername());
        payBill.setShop_id(adoptOrder.getShop_id());
        return payBill;
    }

    @Override
    public PageList<AdoptOrder> queryAdminOrder(AdoptOrderQuery adoptOrderQuery, HttpServletRequest request) {
        LoginInfo loginInfo = LoginContextUtil.getLoginInfo(request);
        // 查询shop_id
        Employee employee = employeeMapper.findByLoginInfoId(loginInfo.getId());
        adoptOrderQuery.setShop_id(employee.getShop_id());
        return super.queryPage(adoptOrderQuery);
    }

    @Override
    public PageList<AdoptOrder> queryUserOrder(AdoptOrderQuery adoptOrderQuery, HttpServletRequest request) {
        LoginInfo loginInfo = LoginContextUtil.getLoginInfo(request);
        // 查询shop_id
        User user = userMapper.loadByLoginInfoId(loginInfo.getId());
        adoptOrderQuery.setUser_id(user.getId());
        return super.queryPage(adoptOrderQuery);
    }

    @Override
    public void cancel(Long orderId) {
        // 通过订单id
        AdoptOrder adoptOrder = adoptOrderMapper.loadById(orderId);
        // 修改状态
        adoptOrder.setState(-1);
        adoptOrderMapper.save(adoptOrder);
        // 查询支付订单
        PayBill payBill = payBillMapper.loadByUnionPaySn(adoptOrder.getPaySn());
        payBill.setState(-1);
        payBill.setUpdateTime(new Date());
        payBillMapper.save(payBill);
    }

    /**
     * 将用户地址转换为订单地址
     * @param userAddress 用户地址
     * @param adoptOrder 领养订单
     * @return 订单地址
     */
    private OrderAddress userAddress2OrderAddress(UserAddress userAddress, AdoptOrder adoptOrder) {
        OrderAddress orderAddress = new OrderAddress();
        BeanUtils.copyProperties(userAddress,orderAddress);

        orderAddress.setOrder_id(adoptOrder.getId());
        orderAddress.setOrderSn(adoptOrder.getOrderSn());
        return orderAddress;
    }

    /**
     * 将领养订单进行赋值
     * @param pet 领养宠物
     * @param user 用户
     * @return 领养订单
     */
    private AdoptOrder petUser2AdoptOrder(Pet pet, User user) {
        // 创建一个领养订单对象
        AdoptOrder order = new AdoptOrder();
        order.setDigest("[摘要]对" + pet.getName() + "领养订单！");
        order.setState(0);
        order.setPrice(pet.getSalePrice());
        String orderSn = CodeGenerateUtils.generateOrderSn(user.getId());
        order.setOrderSn(orderSn);
        String paySn = CodeGenerateUtils.generateUnionPaySn();
        order.setPaySn(paySn);
        // 设置失效时间
        order.setLastPayTime(new Date(System.currentTimeMillis() + 24*60*60*1000));
        order.setPet_id(pet.getId());
        order.setUser_id(user.getId());
        order.setShop_id(pet.getShop_id());
        return order;
    }
}
